package com.ncloud.chnl.business;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.chnl.common.Constant;
import com.ncloud.chnl.entity.Chnl;
import com.ncloud.chnl.mapper.ChnlMapper;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.param.service.SequenceService;

@Service
public class ChnlBusiness {

	@Autowired
	private ChnlMapper chnlMapper;
	@Reference
	private SequenceService sequenceService;
	
	@Transactional
	public void insertChnl(JSONObject json) {
		Chnl chnl = JSON.parseObject(json.toJSONString(), Chnl.class);
		try {
			//判断传入parentId是否存在
			Long parentId = json.getLong("parentId");
			Chnl parent = chnlMapper.getChnl(parentId);
			if(parent == null ) throw new UserException("传入上级渠道不存在！");
			
			String chnlType = json.containsKey("chnlType")?json.getString("chnlType"):parent.getChnlType();
			String chnlLevel = json.containsKey("chnlLevel")?json.getString("chnlLevel"):(Long.parseLong(parent.getChnlLevel())+1)+"";
			Long userId = json.getLong("userID");
			Long chnlId = sequenceService.getSequence("CHNL_ID_SEQ");
			chnl.setChnlId(chnlId);
			chnl.setChnlType(chnlType);
			chnl.setChnlLevel(chnlLevel);
			chnl.setCreateTime(new Date());
			chnl.setUpdateTime(new Date());
			chnl.setCreateUser(userId);
			chnl.setUpdateUser(userId);
			chnl.setState(Constant.CHNL_COMMON_STATE_NORMAL);
			chnlMapper.insertChnl(chnl);
			//拷贝上级渠道产品受理范围
			if("1".equals(parent.getChnlLevel())){
				//拷贝套餐受理范围
				chnlMapper.copyDiscntRelease(parent.getChnlId(),chnl.getChnlId());
				//拷贝价格折扣
				chnlMapper.copyChnlDiscount(parent.getChnlId(),chnl.getChnlId());
			}
		} catch (RuntimeException e) {
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		
	}
	
}
